<?php

namespace app\admin\logic;

use app\common\controller\UserBase;
use app\common\helper\WanX;
use app\common\logic\BaseLogic;
use app\common\model\AiOrder;

class AiLogic extends UserBase
{
    public static function doCreate()
    {
        $id = input('id/d');
        $order = AiOrder::find($id);
        if ($order->task_id) throwError('已经生成');
        $ai = new WanX();
        if ($order->type == 'v1') {
            $result =  $ai->v1($order->prompt,$order->n,$order->size);
        } elseif ($order->type == 'repaint') {
            $result =  $ai->repaint($order);
        } else {
            $result =  $ai->back($order);
        }
        if (isset($result['output'])) {
            $order->save([
                "task_id" => $result['output']['task_id'],
                "task_status" => $result['output']['task_status']
            ]);
            queue('app\common\job\AiOrder@pull',$order->id,5,'pull');
            throwSuccess();
        } else {
            throwError($result['message']);
        }
    }

    public static function doPull()
    {
        $id = input('id/d');
        $order = AiOrder::find($id);
        if (!$order) throwError('订单不存在');
//        if ($order->task_status=='SUCCEEDED') throwError('已经拉取');
        $ai = new WanX();
        $result =  $ai->search($order->task_id);
        throwSuccess($result['output']['task_status'] );
    }

    public static function doSee()
    {
        $id = input('id/d');
        $order = AiOrder::where('id',$id)
            ->with(['image'])->find($id);
        $images = [];
        if ($order) {
            $image = $order->toArray()['image'];
            $images = array_column($image,'cdn_url');
        }
        throwSuccess([
            'order'=>$order,
            'images' => $images
        ]);
    }
}